/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push.application.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.common.utils.context.ContextThead;
import com.foreveross.bsl.push.application.ReceiptService;
import com.foreveross.bsl.push.domain.entity.Push;
import com.foreveross.bsl.push.domain.entity.Push.PushStatusEnum;
import com.foreveross.bsl.push.repository.PushRepository;
import com.google.common.collect.Lists;

/**
 * xxx
 * 
 * @author Wangyi
 * @version v1.0
 * 
 * @date 2013-8-6
 * 
 */
@Named
public class DefaultReceiptService implements ReceiptService {
	
	private static final Logger log = LoggerFactory.getLogger(DefaultReceiptService.class);
	private ExecutorService executorService;
	
	@PostConstruct
	public void init(){
		this.executorService=Executors.newCachedThreadPool();
	}

	private final PushRepository getPushRepository() {
		return new Push().getEntityRepository(PushRepository.class);
	}
	
	@Override
	public void receipt(String deviceId, String msgId, String appId) {
		if(StringUtils.isEmpty(deviceId)){
			throw new IllegalArgumentException("deviceId can not be empty");
		}
		if(StringUtils.isEmpty(msgId)){
			throw new IllegalArgumentException("msgId can not be empty");
		}
		if(StringUtils.isEmpty(appId)){
			throw new IllegalArgumentException("appId can not be empty");
		}
		this.executorService.execute(new ReceiptTask(deviceId, msgId, appId, ContextThead.getThreadVar()));
	}
	
	class ReceiptTask implements Runnable{
		
		private final String msgId, appId, deviceId, dsRouter;
		
		ReceiptTask(String deviceId, String msgId, String appId, String dsRouter){
			this.msgId=msgId;
			this.deviceId=deviceId;
			this.appId=appId;
			this.dsRouter=dsRouter;
		}
		
		@Override
		public void run() {
			String[] msgIds=StringUtils.split(msgId, ',');
			List<Push> pushs = Lists.newArrayListWithExpectedSize(msgIds.length);
			ContextThead.setThreadVar(dsRouter);
			for(String id : msgIds){
				if(StringUtils.isEmpty(id))
					continue;
				Push push = getPushRepository().findOne(appId, deviceId, id);
				if (push != null) {
					pushs.add(push);
				}
				else{
					log.error("回执参数非法！不存在推送实体为: appId:{},deviceId:{},msgId:{}; dsRouter:{}", appId, deviceId,msgId,dsRouter);
				}
			}
			Date now=new Date();
			for(Push push : pushs){
				if (PushStatusEnum.RECEIPT.equals(push.getStatus())) {
					continue;
				}
				push.setStatus(PushStatusEnum.RECEIPT);
				push.setReceiptTime(now);
				getPushRepository().save(push);
			}
		}
	}

}
